package com.zhx.core.social.qq.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

import java.io.IOException;

/**
 * 获取用户信息实现类
 *
 * @author zhanghaixuan
 * @create 2017/11/19-下午8:37
 **/
public class QQImpl extends AbstractOAuth2ApiBinding implements QQ{
    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * AbstractOAuth2ApiBinding
     *
       accessToken : 存放获取到的令牌
       restTemplate : 用来向第三方请求的
     */
    private static final String URL_GET_OPENID = "https://graph.qq.com/oauth2.0/me?access_token=%s";

    private static final String URL_GET_USERINFO = "https://graph.qq.com/user/get_user_info?&oauth_consumer_key=%s&openid=%s";

    private String appId;

    private String openId;

    private ObjectMapper objectMapper = new ObjectMapper();

    public QQImpl(String accessToken,String appId){
        /**
         * 在 AbstractOAuth2ApiBinding 的构造函数中第二个指定了多种方法  有头部的 有当param在连接中请求的
         */
        super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);

        this.appId = appId;
        //构造请求openidurl
        String url = String.format(URL_GET_OPENID,accessToken);

        String result = getRestTemplate().getForObject(url,String.class);


        logger.info("获取openId的结果是:" + result);

        this.openId = StringUtils.substringBetween(result,"\"openid\":\"","\"}");
    }



    @Override
    public QQUserInfo getQQUserInfo(){
            String url = String.format(URL_GET_USERINFO,appId,openId);

            String result = getRestTemplate().getForObject(url,String.class);

            logger.info("获取用户信息的结果是:" + result);
        try {
            QQUserInfo qqUserInfo = objectMapper.readValue(result, QQUserInfo.class);
            qqUserInfo.setOpenId(openId);

            return qqUserInfo;
        } catch (IOException e) {

            e.printStackTrace();
            return null;
        }
    }
}
